var _util = _interopRequireDefault(require("../../../utils/util")), _cardUtil = _interopRequireDefault(require("../../../utils/card-util")), _contactUtil = require("../../../utils/contact-util"), _cardPreview = _interopRequireDefault(require("../../../components/card-preview/card-preview")), _util2 = _interopRequireDefault(require("../../../public/utils/util"));

function _interopRequireDefault(t) {
    return t && t.__esModule ? t : {
        default: t
    };
}

function _toConsumableArray(t) {
    return _arrayWithoutHoles(t) || _iterableToArray(t) || _nonIterableSpread();
}

function _nonIterableSpread() {
    throw new TypeError("Invalid attempt to spread non-iterable instance");
}

function _iterableToArray(t) {
    if (Symbol.iterator in Object(t) || "[object Arguments]" === Object.prototype.toString.call(t)) return Array.from(t);
}

function _arrayWithoutHoles(t) {
    if (Array.isArray(t)) {
        for (var e = 0, a = new Array(t.length); e < t.length; e++) a[e] = t[e];
        return a;
    }
}

function _slicedToArray(t, e) {
    return _arrayWithHoles(t) || _iterableToArrayLimit(t, e) || _nonIterableRest();
}

function _nonIterableRest() {
    throw new TypeError("Invalid attempt to destructure non-iterable instance");
}

function _iterableToArrayLimit(t, e) {
    var a = [], i = !0, r = !1, n = void 0;
    try {
        for (var o, c = t[Symbol.iterator](); !(i = (o = c.next()).done) && (a.push(o.value), 
        !e || a.length !== e); i = !0) ;
    } catch (t) {
        r = !0, n = t;
    } finally {
        try {
            i || null == c.return || c.return();
        } finally {
            if (r) throw n;
        }
    }
    return a;
}

function _arrayWithHoles(t) {
    if (Array.isArray(t)) return t;
}

function _objectSpread(e) {
    for (var t = 1; t < arguments.length; t++) {
        var a = null != arguments[t] ? arguments[t] : {}, i = Object.keys(a);
        "function" == typeof Object.getOwnPropertySymbols && (i = i.concat(Object.getOwnPropertySymbols(a).filter(function(t) {
            return Object.getOwnPropertyDescriptor(a, t).enumerable;
        }))), i.forEach(function(t) {
            _defineProperty(e, t, a[t]);
        });
    }
    return e;
}

function _defineProperty(t, e, a) {
    return e in t ? Object.defineProperty(t, e, {
        value: a,
        enumerable: !0,
        configurable: !0,
        writable: !0
    }) : t[e] = a, t;
}

var app = getApp(), MINIAPPGUIDEKEY = "add-mine-miniapp-guide", MINIAPPQRCODE = "miniappqrcode", _global = global, api = _global.api, user = _global.user, config = _global.config, socket = _global.socket;

Page({
    data: {
        emptyTip: "你还没有名片哦。赶紧去创建吧！",
        page: "index",
        moreTip: !1,
        isIOS: app.globalData.isIOS,
        tabcommonlistAni: {},
        exchangeCount: 0
    },
    mixins: [ _cardPreview.default ],
    handleRedirect: function(t) {
        var e = this;
        t.scene && (console.log(t.scene, "通过二维码进入"), api.weapp.getdatafromscene({
            loading: "正在跳转",
            data: {
                scene: t.scene,
                app: config.WX_APP_NAME
            }
        }).then(function(t) {
            return e.redirectToPage(t.data);
        }));
    },
    redirectToPage: function() {
        var t = 0 < arguments.length && void 0 !== arguments[0] ? arguments[0] : {}, e = t.type, a = t.params, i = t.path;
        switch (e) {
          case "loginpc":
            return void (0, _contactUtil.loginPcMethod)(a);

          case "minicard":
          case "printminicard ":
          case "minicardqrcode":
          case "printminicard":
          case "miniprintminicard":
            this.$report("card_in_scan_open"), a.from = 2, a.type = "scan";
            var r = "/pages/card/view/view";
            return "1" === (this.$app.query = a).scenetype && (r = "/toolPackage/card-exchange/view/view"), 
            void this.$route("".concat(r, "?").concat(_util2.default.serialize(a)), "redirect");

          case MINIAPPQRCODE:
            return this.redirect = {
                type: e,
                params: a
            }, void this.relateuserMiniapp(a);

          case "minicardactivity":
            return void this.loadActivity(a.activityid);

          case "0":
            return void this.$route("/miniweb/pages/website/index/index?sid=" + a.sid, "redirect");

          case "1":
          case "2":
          case "3":
          case "4":
            var n = _util.default.createModelUrl(config.model, _objectSpread({}, a, {
                modid: e
            }));
            return void this.$route(n, "redirect");
        }
        if (i) {
            var o = _util2.default.parseUrl(i).query, c = void 0 === o ? {} : o;
            this.$app.query = c, this.$route(i);
        }
    },
    loadActivity: function(t) {
        var i = this;
        api.minicard.activity.detail({
            data: {
                id: t,
                from: "view"
            }
        }).then(function(t) {
            var e = t.code, a = t.data;
            0 === e ? i.activityRedirecct(a) : i.$route("/toolPackage/activity/empty/empty", "redirect");
        }).catch(wx.hideLoading);
    },
    activityRedirecct: function(t) {
        var e = t.handMember, a = JSON.parse(t.landingpage), i = Math.ceil(Date.now() / 1e3), r = "0000-00-00 00:00:00" === t.expiretime ? 0 : new Date(t.expiretime.replace(/-/g, "/"));
        if (r && r < i) return this.$route("/toolPackage/activity/empty/empty", "redirect");
        t.landingpageisexists || (a.type = "card");
        var n = "sid=".concat(a.sid, "&cardid=").concat(e.cardid, "&guid=").concat(e.guid, "&fromuid=").concat(e.uid);
        switch (this.$put("activity.service", {
            service: e,
            activity: t
        }), a.type) {
          case "card":
            return void this.$route("/pages/card/view/view?guid=".concat(e.guid, "&cardid=").concat(e.cardid, "&type=scan&from=2"), "redirect");

          case "model":
            var o = _util.default.createModelUrl(config.model, _objectSpread({}, a.data, {
                op: "link"
            }));
            return void this.$route(o + "&" + n, "redirect");

          case "site":
            return void this.$route("/miniweb/pages/website/index/index?".concat(n), "redirect");

          case "bargaining":
            return void this.$route("/miniweb/pages/common/bargaining/view/view?bargainid=".concat(a.data.id, "&name=").concat(a.data.name, "&").concat(n), "redirect");
        }
    },
    onLoad: function(t) {
        this.handleRedirect(t);
        var e = this.$appData.card;
        this.setCard(e), this.initSocket(), this.initEvents(), e.guid && this.postTick();
    },
    signinSuccess: function() {
        this.onPullDownRefresh();
    },
    initSocket: function() {
        var d = this;
        [ [ "views", "view_card_v2" ], [ "favs", "card_fav" ], [ "likes", "add_card_like" ] ].forEach(function(t, c) {
            var e = _slicedToArray(t, 2), s = e[0], a = e[1];
            socket.on("event." + a, function(t) {
                var e = t.params.fromcardid, a = d.data, i = a.badges, r = void 0 === i ? [] : i, n = a.card;
                if (!e || +e == +n.cardid) {
                    r[c] = 1;
                    var o = "origin".concat(s.replace(/^[a-z]/, function(t) {
                        return t.toUpperCase();
                    }));
                    n[o] = +n[o] + 1, n[s] = _util2.default.convertNumber(n[o]), d.setData(_defineProperty({
                        card: n,
                        badges: r
                    }, "tabcommonlistAni.".concat(s), !0)), wx.sleep(1e3).then(function() {
                        d.setData(_defineProperty({}, "tabcommonlistAni.".concat(s), !1));
                    });
                }
            });
        });
    },
    initEvents: function() {
        var r = this;
        [ [ "card.change", function(t) {
            var e = r.redirect || {}, a = e.type, i = e.params;
            a && i && !t.cardid && a === MINIAPPQRCODE ? r.$route("/pages/card/create/create?uid=".concat(i.uid), "redirect") : (_cardUtil.default.waitJoinModal(), 
            r.setCard(t));
        } ], [ "card.badges.change", function(t) {
            return r.setData({
                badges: t
            });
        } ] ].forEach(function(t) {
            return r.$addListener.apply(r, _toConsumableArray(t));
        });
    },
    onPullDownRefresh: function() {
        this.data.card.cardid ? this.getInteractData() : this.selectComponent("#track").onPullDownRefresh(), 
        (0, _contactUtil.loadContact)(wx.stopPullDownRefresh);
    },
    onReachBottom: function() {
        (this.data.card || {}).cardid || this.selectComponent("#track").onReachBottom();
    },
    onShow: function() {
        var e = this;
        this.$take("contact.join.success") && wx.setTimeout(function() {
            wx.showToast({
                title: "加入成功",
                duration: 500
            });
        }, 500), this.$take("card.success.share") && this.setData({
            giveCardShown: !0
        }), this.$take("card.success") && wx.showModal({
            content: "如何提高你的名片被访问率？试试新的转发标题与卡片吧!",
            confirmText: "去看看",
            success: function(t) {
                return t.confirm && e.$route("/pages/card/transferword/transferword");
            }
        });
    },
    onHide: function() {
        if (this.pageShare) return this.pageShare = !1;
        this.data.shown && this.setData({
            shown: !1
        });
    },
    onReady: function() {
        var e = this;
        wx.showShareMenu({
            withShareTicket: !0
        }), user.getTokens(function(t) {
            e.isLogin = !!t, t || (user.listenToken(function() {
                return e.isLogin = !0;
            }), e.signinModal = e.selectComponent("#signinModal"));
        });
    },
    postTick: function() {
        var e = this;
        api.minicard.post.tick().then(function(t) {
            e.setData({
                hasNewPost: t.data.hasNewPost
            });
        });
    },
    onTabItemTap: function() {
        app.reportAnalytics("tabbar_card");
    },
    relateuserMiniapp: function(t) {
        api.minicard.miniapp.relateuser({
            data: t
        });
    },
    setCard: function(t) {
        var e = {
            card: t
        };
        this.setData(e), t.cardid && t.guid ? (this.downWxAvatar(t), this.getInteractData(), 
        wx.showTabBar()) : (wx.hideTabBar(), this.hideTabBar = !0);
    },
    downWxAvatar: function(e) {
        _cardUtil.default.downWxAvatar(e.avatar).then(function(t) {
            api.weappcard.update({
                name: "avatar",
                filePath: t,
                formData: {
                    type: e.type,
                    cardid: e.cardid
                }
            }).then(function() {
                return _cardUtil.default.renew();
            });
        });
    },
    getInteractData: global.debounce(function(t) {
        var a = this;
        this.observerCard(), this.loadExchangeCount();
        var e = this.selectComponent("#visitor");
        e && e.init();
        var i = [ "views", "favs", "likes" ];
        api.weappcard.msgtip({
            data: {
                readtype: 0,
                cardid: this.data.card.cardid
            }
        }).then(function(t) {
            var e = t.data;
            a.$setData({
                badges: i.map(function(t) {
                    return e[t];
                })
            });
        });
    }, 1e3, {
        leading: !0,
        trailing: !1
    }),
    loadExchangeCount: function() {
        var e = this, t = this.data.card;
        api.minicard.card.getexchangecardhistorylist({
            data: {
                tocardid: t.cardid,
                status: 0,
                limit: 1
            }
        }).then(function(t) {
            e.setData({
                exchangeCount: t.data.count
            });
        });
    },
    onViewerCancel: function() {
        wx.showTabBar();
    },
    viewCommonList: function(t) {
        var e = t.currentTarget.dataset.type, a = this.data.card, i = a.cardid, r = a.uid;
        this.$report("home_tap_".concat(e)), this.$route("/pages/tabcommonlist/tabcommonlist?listType=".concat(e, "&cardid=").concat(i, "&uid=").concat(r));
    },
    onMoreTap: function(t) {
        var e = t.currentTarget.dataset, a = e.type, i = e.path, r = {
            shown: !1
        };
        switch (a) {
          case "activity":
          case "official":
            this.$route("/toolPackage/".concat(i));
            break;

          case "invite":
            r.shown = !0;
            break;

          case "card-scan":
            this.$route("/pages/card/scanner/scanner?mode=contactIndex");
            break;

          case "mycode":
            this.cardCodeShown(), wx.hideTabBar();
            break;

          case "card-exchange":
            this.$route("/toolPackage/card-exchange/index/index?applycount=".concat(this.data.exchangeCount)), 
            this.setData({
                exchangeCount: 0
            });
            break;

          case "spread":
            this.$route("/pages/card/transferword/transferword");
            break;

          case "poster":
            this.setData({
                hasNewPost: 0
            });

          default:
            this.$route("/toolPackage/".concat(i));
        }
        this.setData(r), this.reportMoreTool(a);
    },
    reportMoreTool: function(t) {
        this.$report({
            mycode: "home_tap_card_code",
            "card-exchange": "home_tap_card_exchange",
            poster: "card_app_poster",
            "card-scan": "home_tap_card_shoot",
            "card-print": "card_app_poster_print",
            wallpaper: "card_app_poster_wallpaper",
            invite: "card_app_poster_invite",
            activity: "card_app_poster_market",
            official: "card_app_poster_official"
        }[t]);
    },
    onMoreShown: function() {
        var t = this.data.shown;
        this.setData({
            shown: !t
        }), t || app.reportAnalytics("card_app");
    },
    cardShareConfig: function(t) {
        var e = this;
        return this.$report("self_card_share"), wx.sleep(1e3).then(function() {
            e.setData({
                giveCardShown: !1
            });
        }), _cardUtil.default.shareConfig(t);
    },
    hideGiveCardGuideModal: function() {
        wx.setTimeout(this.checkIsShowGuide.bind(this), 500);
        var t = this.data, e = t.showMineMiniappGuide, a = t.giveCardShown, i = {};
        e && (i.showMineMiniappGuide = !1), a && (i.giveCardShown = !1), this.setData(i);
    },
    checkIsShowGuide: function() {
        var t = this;
        wx.getStorage({
            key: MINIAPPGUIDEKEY,
            fail: function() {
                t.setData({
                    showMineMiniappGuide: !0
                });
            }
        });
    },
    mineMiniappGuide: function() {
        var t = this;
        wx.setStorage({
            key: MINIAPPGUIDEKEY,
            data: 1,
            success: function() {
                t.setData({
                    showMineMiniappGuide: !1
                });
            }
        });
    },
    toggleAuthModal: function() {
        var t = this.selectComponent("#authModal");
        t && t.toggle();
    },
    pageScrollTop: function() {
        this.data.isSticky && (this.setData({
            isSticky: !1
        }), wx.pageScrollTo({
            scrollTop: 0,
            duration: 1
        }), wx.sleepSync(200));
    },
    onShareAppMessage: function(t) {
        this.pageShare = !0;
        var e = this.data.card;
        if (!e || !e.guid) return {};
        this.pageScrollTop();
        var a = t.target ? t.target.dataset.type : "";
        return this.hideGiveCardGuideModal(), "contact" === a ? (0, _contactUtil.inviteShareConfig)({
            params: {
                guid: e.guid
            }
        }) : this.cardShareConfig(e);
    },
    onView: function() {
        var t = this.data.card, e = t.guid, a = t.cardid;
        this.$report("home_view_card"), this.$route("/pages/card/view/view?guid=".concat(e, "&cardid=").concat(a, "&mine=1"));
    },
    reportVistor: function() {
        this.$report("home_tap_recently_visitor");
    }
});